<?php
namespace app\common\model;

use ball\UpayMiniApp;
use ball\WechatApp;
use app\admin\model\TerminalApp;
use app\admin\model\SubscribeOrder;
use app\admin\model\SubscribeRecord as recordModel;
use app\common\model\UserScoreLog;
use app\common\model\User;
use think\facade\Db;
use think\facade\Log;
class Payment
{
    public static function payment( SubscribeOrder $order,$user){
      $orderArray = $order->toArray();
      $orderArray['openid'] = $user['openid'];
      $orderArray['notify_url'] = request()->domain().'/notify.php';
      if($orderArray['pay_mode'] == 'wechat'){
        return WechatApp::precreate($orderArray);
      }else{
        $response = self::upay($orderArray);
        if($response !== false && $response['result_code'] == 'PRECREATE_SUCCESS'){
            $order->trade_sn = $response['data']['sn'];
            $order->save();
            return $response['data']['wap_pay_request'];
        }
      }
      return false;
    }
    public static function upay(array $order){
      $terminal = TerminalApp::where('device_id', 'RHminiApp')->find();
      $UpayApp = new  UpayMiniApp();
      //更新当天的key;
      if(date('Ymd',$terminal->update_time) < date('Ymd')){
        $rlt  = $UpayApp->checkin($terminal->toArray());
        $terminal->terminal_key = $rlt['terminal_key'];
        $terminal->save();
      }
      return $UpayApp->precreate($order,$terminal->toArray());
    }

    public static function upayQuery($out_trade_no){
      $terminal = TerminalApp::where('device_id', 'RHminiApp')->find();
      $UpayApp = new  UpayMiniApp();
      //更新当天的key;
      if(date('Ymd',$terminal->update_time) < date('Ymd')){
        $rlt  = $UpayApp->checkin($terminal->toArray());
        $terminal->terminal_key = $rlt['terminal_key'];
        $terminal->save();
      }
      return $UpayApp->query($out_trade_no,$terminal->toArray());
    }
    public static function verify($out_trade_no){
      $order = SubscribeOrder::where('out_trade_no',$out_trade_no)->find();
      if(empty($order)){
        return false;
      }
      if($order->pay_status == '1'){
        return true;
      }
      $isopen = get_sys_config('is_open');
      if($order->pay_mode =='wechat'){
        $message = WechatApp::query($out_trade_no);
        if(isset($message['trade_state']) && $message['trade_state'] == 'SUCCESS'){
          $order->trade_no = $message['transaction_id'];
          $order->pay_status = 1;
          $order->pay_time= time();
          $order->status = 1;
          $order->state = $isopen=='1'?1:2;
          if($order->out_trade_type == '6'){
            recordModel::where('order_id',$order['id'])->where('status',0)->save(['status'=>1,'state'=>$isopen=='1'?2:3]);
            Db::name('UserLog')->save(['type'=>1,'user_id'=>$order->user_id,'content'=>'支付预约订单'.$order->order_amount.'元']);
          }
          if(in_array($order->out_trade_type,['1','2'])){
            Db::name('UserLog')->save(['type'=>1,'user_id'=>$order->user_id,'content'=>'支付入场券订单'.$order->order_amount.'元']);
          }
          if(in_array($order->out_trade_type,['3','4','5'])){//设置会员有效期
            $m = '';
            $user = User::find($order->user_id);
            
            switch ($order->out_trade_type) {
              case '3':
                $m='月';
                if($user['auth_end'] > time()){
                  $user['auth_end'] = strtotime('+1 month', $user['auth_end']);
                }else{
                  $user['auth_start'] = time();
                  $user['auth_end'] = strtotime('+1 month', time());
                }
                break;
              case '4':
                $m='季';
                if($user['auth_end'] > time()){
                  $user['auth_end'] = strtotime('+3 months', $user['auth_end']);
                }else{
                  $user['auth_start'] = time();
                  $user['auth_end'] = strtotime('+3 months', time());
                }
                break;
              case '5':
                $m='年';
                if($user['auth_end'] > time()){
                  $user['auth_end'] = strtotime('+1 year', $user['auth_end']);
                }else{
                  $user['auth_start'] = time();
                  $user['auth_end'] = strtotime('+1 year', time());
                }
              break;
            }
            $user->group_id =3;
            
            UserScoreLog::create([
              "user_id"=>$user->id,
              "score"=> $order->order_amount,
              "before"=>$user->score,
              "after"=>$user->Score+$order->order_amount,
              "memo"=>'购买至尊会员'.$m.'卡',

            ]);
            $user->score = $user['score'] + $order->order_amount;
            $user->save();
            Db::name('UserLog')->save(['type'=>2,'user_id'=>$order->user_id,'content'=>'购买至尊会员'.$m.'卡;有效期至']);
            $order->state = 3;
          }
          $order->save();
          $orderDetail = $order->toArray();
          $orderDetail['openid'] = Db::name('User')->where('id',$order->user_id)->value('openid');
          WechatApp::shopping($orderDetail);
          return true;
        }
      }else{
        $message = self::upayQuery($out_trade_no);
        Log::info(json_encode($message));
        if($message['result_code'] == 'SUCCESS' && $message['data']['order_status'] == 'PAID'){
          $order->pay_status = 1;
          $order->pay_time= time();
          $order->status = 1;
          $order->state = $isopen=='1'?1:2;
          if($order->out_trade_type == '6'){
            recordModel::where('order_id',$order['id'])->where('status',0)->save(['status'=>1,'state'=>$isopen=='1'?1:2]);
            Db::name('UserLog')->save(['type'=>1,'user_id'=>$order->user_id,'content'=>'支付订单'.$order->order_amount.'元']);
          }
          if(in_array($order->out_trade_type,['1','2'])){
            Db::name('UserLog')->save(['type'=>2,'user_id'=>$order->user_id,'content'=>'支付入场券订单'.$order->order_amount.'元']);
          }
          if(in_array($order->out_trade_type,['3','4','5'])){//设置会员有效期
            $m = '';
            $user = User::find($order->user_id);
            
            switch ($order->out_trade_type) {
              case '3':
                $m='月';
                if($user['auth_end'] > time()){
                  $user['auth_end'] = strtotime('+1 month', $user['auth_end']);
                }else{
                  $user['auth_start'] = time();
                  $user['auth_end'] = strtotime('+1 month', time());
                }
                break;
              case '4':
                $m='季';
                if($user['auth_end'] > time()){
                  $user['auth_end'] = strtotime('+3 months', $user['auth_end']);
                }else{
                  $user['auth_start'] = time();
                  $user['auth_end'] = strtotime('+3 months', time());
                }
                break;
              case '5':
                $m='年';
                if($user['auth_end'] > time()){
                  $user['auth_end'] = strtotime('+1 year', $user['auth_end']);
                }else{
                  $user['auth_start'] = time();
                  $user['auth_end'] = strtotime('+1 year', time());
                }
              break;
            }
            $user->group_id =3;
            
            UserScoreLog::create([
              "user_id"=>$user->id,
              "score"=> $order->order_amount,
              "before"=>$user->score,
              "after"=>$user->Score+$order->order_amount,
              "memo"=>'购买至尊会员'.$m.'卡',

            ]);
            $user->score = $user['score'] + $order->order_amount;
            $user->save();
            Db::name('UserLog')->save(['type'=>2,'user_id'=>$order->user_id,'content'=>'购买至尊会员'.$m.'卡;有效期至'.date('Y-m-d',$user->auth_end)]);
            $order->state = 3;
          }
          
          $order->save();
          return true;
        }
      }
      return false;
    }
}